import asyncio
import time
class ContextMgr:
    def __init__(self):
        self.conn = None
    def do_something(self):
        print(self.conn)
        print("do_something")
    def __enter__(self):
        print("__enter__")
        #初始化数据库连接
        time.sleep(5)
        self.conn = 1
        #注意要返回 self
        return self
    def __exit__(self, exc_type, exc_val, exc_tb):
        #模拟释放数据库连接
        self.conn = None
        print("__exit__")

# with ContextMgr() as f:
#     f.do_something()


class AsyncContextMgr:
    def __init__(self):
        self.conn = None
    def do_something(self):
        print(self.conn)
        print("do_something")
    async def __aenter__(self):
        print("__enter__")
        #初始化数据库连接
        time.sleep(5)
        self.conn = 1
        #注意要返回 self,否则外部 as 变量  为 None
        return self
    async def __aexit__(self, exc_type, exc_val, exc_tb):
        #模拟释放数据库连接
        self.conn = None
        print("__exit__")


async def test():
    async with AsyncContextMgr() as f:
        f.do_something()

asyncio.run(test())